<?php
/*
 * program:	均源
 * author:	雨中漫步 & 上善若水 & qhxin
 * email:	qhxin@qhxin.com
 * date:	2014/11/11
 * description:	又是一年双十一，不能剁手，就写点东西吧~~~~~~
 */

defined('IN_SCHOOL') or die();

/*{TranslateTagBegin}*/
class UpFile{
	
	private $allow_type;
	private $allow_size;
	private $store_path;
	private $new_path;
	
	public $file_info;
	public $file_ext;
	public $error_code;
	public $upload_path;
	
	public function __construct($options){
		
		if(isset($options[2]) && !empty($options[2])){
			$this->allow_type = $options[2];
		}else{$this->allow_type = array('jpg','jpeg','png','gif','bmp');}
		
		if(isset($options[1]) && !empty($options[1])){
			$this->allow_size = $options[1];
		}else{$this->allow_size = 2097152;}//2MB
		
		if(isset($options[0]) && !empty($options[0])){
			$this->store_path = $options[0];//相对于根目录，以/结尾
		}else{	die('err: upload path error.');}
		
		$this->file_info = isset($_FILES['file']) ? $_FILES['file'] : array();
	}
	
	public function upload(){
		if(!isset($this->file_info['name']) || empty($this->file_info['name'])){
			$this->error_code = 11;return;//未检测到上传
		}
		if(!$this->checkext()){
			$this->error_code = 12;return;//文件格式不能上传
		}
		if(!$this->checksize()){
			$this->error_code = 13;return;//文件太大
		}
		if($this->find_error())return;//其他错误
		
		$this->setpath();
		
		if($this->upmov()){
			$this->error_code = 0;//上传成功
		}else{
			$this->error_code = 14;//上传失败
		}
	}
	
	private function checkext(){
		$str = $this->file_info['name'];
		$arr = explode('.',$str);
		$this->file_ext = strtolower($arr[count($arr)-1]);
		return in_array($this->file_ext,$this->allow_type);
	}
	
	private function checksize(){
		return ($this->file_info['size'] <= $this->allow_size);
	}
	
	private function setpath(){
		$new_name = md5(md5($this->file_info['name']).time().mt_rand(0,1000));
		$tocreate = date('Ym');
		$dirname = IN_APP.$this->store_path.$tocreate;
		if(!is_dir($dirname)){
			mkdir($dirname,0700);
		}
		$this->new_path = $dirname.'/'.$new_name;
		while($this->check_file()){
			$new_name .= '0';
			$this->new_path = $dirname.'/'.$new_name;
		}
		$this->new_path .= '.'.$this->file_ext;
		$this->upload_path = $this->store_path.$tocreate.'/'.$new_name.'.'.$this->file_ext;
	}
	
	private function check_file(){
		if(file_exists($this->new_path.'.'.$this->file_ext)){
			return true;
		}else{
			return false;
		}
	}
	
	private function find_error(){
		$this->error_code = $this->file_info['error'];
		if($this->error_code>0){
			return true;
		}
		return false;
	}
	
	private function upmov(){
		return move_uploaded_file($this->file_info['tmp_name'],$this->new_path);
	}

}
/*{TranslateTagEnd}*/

?>